<template>
  <div class="form-content">
    <!-- 表格查询 -->
    <div class="table-search">
      <el-form ref="form" :model="formInline" :rules="rules" :inline="true"   class="demo-form-inline">
        <el-form-item prop="imei">
          <el-input v-model="formInline.imei" clearable placeholder="请输入imei" @clear="clearChange"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search('form')">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-upload
            style="display:inline-block;"
            action="/xiaoyi/devtty/addDevs.action"
            :data="{ sign: sign }"
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            :on-error="handleError"
            name="uploadFile"
            :show-file-list="false"
            :multiple="false" >
            <el-button  type="primary">设备导入</el-button>
          </el-upload>
          <el-button type="primary" style="margin-left: 10px;"  @click="multiSale">批量出库</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="form-main">
      <!-- 表头标题 -->
      <div class="tb_title">库存设备</div>
      <!-- 表格 -->
      <div class="listfile">
        <el-table
          v-loading="loading"
          :data="tableData"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          :height="tableHeight"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="imei" label="IMEI" width="140"></el-table-column>
          <el-table-column prop="deviceName" label="设备名称" width="140"></el-table-column>
          <!-- <el-table-column prop="deviceCode" label="设备编码" ></el-table-column> -->
          <!-- <el-table-column prop="deviceCode" label="自定义编码" width="100"></el-table-column> -->
          <el-table-column prop="statusinfo" label="设备状态" width="90"></el-table-column>

          <!-- <el-table-column prop="projectName" label="所属项目" width="200"></el-table-column> -->
          <!-- <el-table-column prop="projectType" label="项目类型" width="100"></el-table-column> -->
          <el-table-column prop="createTime" label="入库时间" width="120"></el-table-column>
          <!-- <el-table-column prop="saleTime" label="销售时间"></el-table-column> -->
          <!-- <el-table-column prop="userName" label="用户"></el-table-column>   -->
          <!-- <el-table-column prop="deviceRemark" label="设备备注"></el-table-column> -->
          <!-- <el-table-column prop="versionRemark" label="版本备注"></el-table-column> -->
          <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>

          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <!-- <el-button @click="handleClick(scope.row)" icon="el-icon-star-off" type="warning" size="mini">查看</el-button> -->
              <el-button
                size="mini" type="primary"
                @click="handleSale(scope.$index, scope.row)">出库</el-button>
              <!-- <el-button
                size="mini"
                type="danger" icon="el-icon-delete"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="table_page" >
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        ></el-pagination>
      </div>

    </div>

    <!-- 子组件 -->
    <storeDeviceModal ref="outbound_device" @submit="submitChange" :multiData="multiData" :detail='detail' />
  </div>
</template>

<script>
import storeDeviceModal from "./store-device-modal.vue"
import { loadDevice, saleDevice, searchByImei, multiOutboundDevice  } from '@/api/device'
import md5 from 'md5'
import { nowDate } from '@/utils/times'
  export default {
    components: {storeDeviceModal},
    data() {
      const validImei = (rule, value, callback)=> {
        console.log(rule,value)
          if(value && value.trim().length > 4) {
            callback()
          } else {
            callback(new Error('IMEI不能少于5位'))
          }
      }
      return {
        tableHeight: 'calc(100vh - 296px)',
        multiData: [],
        detail: {},
        sign: md5(nowDate()),
        fileList: [],
        totalCount: 0, //总条数，总共有多少条数据
        currentPage: 1, // 当前页
        pageSize: 10, // 每页显示多少条
        addEdit_data: {},
        loading: true,
        tableData: [ ],
        formInline: {
          imei: '',
        },
        rules: {
          imei: [ {validator: validImei, trigger: 'blur'}]
        }
      }
    },
    methods: {
      handleSelectionChange(data){
        // this.multiData = data.map(v => v.imei)
        this.multiData = [...data]
        console.log(data,  this.multiData)
      },
      handleBeforeUpload(file){
        console.log(file)
        let type = file.type
        if( file.name.endsWith('.xlsx') || file.name.endsWith('.xls') ) {
          } else {
            this.$message.warning(`导入的文件不支持${type}类型`)
            return false
        }
      },
      handleSuccess(response, file, fileList) {
        console.log(response, file, fileList);
        if(response.statusCode == '200'){
          this.$message.success(`文件上传成功！`)
          this.currentPage = 1
          this.loadData()
        }else {
          this.$message.error(`文件上传失败！`)
        }
      },
      handleError(err, file, fileList) {
        console.log(err, file, fileList);
        this.$message.error(`文件上传失败！`)
      },
      // 批量出库
      multiSale(){
        this.$refs.outbound_device.modal1 = true;
        this.$refs.outbound_device.title_name = '批量出库设备';
        // if(this.multiData.length == 0){
        //   this.$message.warning('请选择您需要销售的设备.')
        //   return
        // } else{
        // }
      },

      //单个出库
      submitChange (data) {
        console.log(data, 'data')
        multiOutboundDevice({ ...data}).then(res => {
          if(res.statusCode == '200'){
            this.$message.success('出库成功。')
            this.loadData()
          } else {
            this.$message.error(res.statusMsg)
          }
        }).catch()

      },
      search() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.currentPage = 1
            this.loadData()
          }
        })
      },
      clearChange(){
        // this.currentPage = 1
        // this.loadData()
      },
      //销售
      handleSale(index, row) {
        this.detail = JSON.parse(JSON.stringify(row));
        this.$refs.outbound_device.modal1 = true;
        this.$refs.outbound_device.title_name = '出库设备';
      },
      // 分页
      handleCurrentChange(newPage) {
        this.currentPage = newPage
        this.loadData()
      },
      //每页
      handleSizeChange(val) {
        this.pageSize = val
        this.loadData()
      },
      loadData(){
        if(this.formInline.imei){
          let imei = this.formInline.imei.substr(this.formInline.imei.length -5, 5)
          searchByImei({
            imei: imei,
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            deviceStatus: 0,
          }).then(res => {
            this.tableData = res.data.content;
            this.totalCount = res.data.total;
          }).catch()

        } else {
          loadDevice({ deviceStatus: 0, pageNum: this.currentPage, pageSize: this.pageSize}).then(res => {
            this.tableData = res.data.content;
            this.totalCount = res.data.total;
          }).catch()

        }
      }
    },
    created(){
      this.loadData()
    },
    mounted(){
      this.loading = false;
    },
    destroyed() {
      this.$destroy();
      this.historyData = [];
      this.page_Data = [];
    },
    watch: {
      formInline: {
        handler: function(val){
          if(val.imei) {
          } else {
            this.currentPage = 1
            this.loadData()
          }
        },
        deep: true
      }
    }
  }
</script>
